<template>
    <el-dialog class="create-mybatis-dialog" title="生成MyBatis" width="85%"
               :visible.sync="visible" :before-close="handleClose">


        <div>
            <template v-for="table in tables">
                <h4 v-text="table.name"></h4>
                <p>mapper</p>
                <ac-high-light v-model="table.mapper"></ac-high-light>

                <template v-if="table.select">
                    <p>select</p>
                    <ac-high-light v-model="table.select"></ac-high-light>
                </template>

                <template v-if="table.selectList">
                    <p>selectList</p>
                    <ac-high-light v-model="table.selectList"></ac-high-light>
                </template>

                <template v-if="table.selectPage">
                    <p>selectPage</p>
                    <ac-high-light v-model="table.selectPage"></ac-high-light>
                </template>

                <template v-if="table.selectPageTotal">
                    <p>selectPageTotal</p>
                    <ac-high-light v-model="table.selectPageTotal"></ac-high-light>
                </template>

                <template v-if="table.selectByKeyword">
                    <p>selectByKeyword</p>
                    <ac-high-light v-model="table.selectByKeyword"></ac-high-light>
                </template>

                <template v-if="table.selectTotalByKeyword">
                    <p>selectTotalByKeyword</p>
                    <ac-high-light v-model="table.selectTotalByKeyword"></ac-high-light>
                </template>

                <template v-if="table.insert">
                    <p>insert</p>
                    <ac-high-light v-model="table.insert"></ac-high-light>
                </template>

                <template v-if="table.update">
                    <p>update</p>
                    <ac-high-light v-model="table.update"></ac-high-light>
                </template>


                <br><br>
                <hr>
            </template>
        </div>


        <div slot="footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="success" @click="saveClick">保存文件</el-button>
        </div>

        <template>
            <ac-select-mybatis-dialog
                    v-if="ui.selectMyBatisDialog.visible"
                    :dialogVisible="ui.selectMyBatisDialog.visible"
                    :dialogVisible.sync="ui.selectMyBatisDialog.visible"
                    @onSubmit="handleSelectSubmit"
                    @onClose="handleClose">

            </ac-select-mybatis-dialog>

            <ac-select-keyword-dialog
                    v-if="ui.selectKeywordDialog.visible"
                    :dialogVisible="ui.selectKeywordDialog.visible"
                    :dialogVisible.sync="ui.selectKeywordDialog.visible"
                    :fields="fields"
                    @onSubmit="handleSelectKeywordSubmit"
                    @onClose="handleClose">

            </ac-select-keyword-dialog>
        </template>
    </el-dialog>
</template>

<script type="text/ecmascript-6">
    import AcSelectMybatisDialog from "./SelectMyBatisDialog";
    import AcHighLight from "../common/HighLightTextArea";
    import AcSelectKeywordDialog from "./SelectKeywordDialog";

    import mapper from '../model/mapper'
    import mapperXML from '../model/mapperXML'
    import select from '../model/select'
    import insert from '../model/insert'
    import update from '../model/update'

    import path from 'path';
    import fs from 'fs';

    /**
     * @author 白雨浓
     * @date 2018/1/23 11:54
     *
     * 创建MyBatis窗口
     * （由于selectByKeyword无法确定是哪个表，无法阻止向下执行，所以目前只能单表生成，不能多选）
     **/
    export default{
        components: {
            AcSelectKeywordDialog,
            AcHighLight,
            AcSelectMybatisDialog
        },
        name: 'AcCreateMybatisDialog',
        props: ['dialogVisible', 'tableNames', 'config',],
        data(){
            return {
                ui: {
                    selectMyBatisDialog: {visible: false},
                    selectKeywordDialog: {visible: false}
                },
                visible: this.dialogVisible,
                selects: [], /*层*/
                tables: [],
                fields: [],
                name: '', /*当前的表名*/
            }
        },
        mounted(){
            this.$nextTick(() => {
                this.ui.selectMyBatisDialog.visible = true;
            })
        },
        methods: {
            saveClick(){
                let projectPath = this.config.projectPath;

                if (projectPath[projectPath.length - 1] !== '/')
                    projectPath += '/';
                let buffPath = projectPath;
                projectPath += 'src/main/java/';
                projectPath += this.config.packageName.replace(/\./g, '/');

                if (!fs.existsSync(path.join(projectPath))) {
                    this.$$msg.error('工程目录不存在，请检查基础设置-ProjectPath');
                    return;
                }

                let myBatisXMLPath = this.config.myBatisXMLPath;
                if (this.config.myBatisXMLPath[0] !== '/')
                    myBatisXMLPath = '/' + myBatisXMLPath;
                if (myBatisXMLPath[myBatisXMLPath.length - 1] !== '/')
                    myBatisXMLPath = buffPath + 'src' + this.config.myBatisXMLPath + '/';
                else
                    myBatisXMLPath = buffPath + 'src' + this.config.myBatisXMLPath;

                const table = this.tables[0];

                let clsName = this.$str.toCamel(this.name);
                clsName = clsName.substring(0, 1).toUpperCase() + clsName.substring(1);

                let entityName = clsName + 'Entity';

                this.$prompt('请输入实体类的PackageName', '输入', {
                    inputValue: this.config.packageName + '.entity.' + entityName
                }).then(({value}) => {
                    const xml = mapperXML.xml(this, this.name, value, table);
                    this.writeFile(projectPath, `mapper`, `${clsName}Mapper.java`, table.mapper);
                    this.writeFile(myBatisXMLPath, '', `${clsName}Mapper.xml`, xml);
                    this.handleClose();
                });
            },
            writeFile(projectPath, packageName, filename, text){
                const filePath = path.join(projectPath + `/${packageName}/`, filename);

                if (fs.existsSync(filePath)) {
                    this.$notify({
                        title: '提示',
                        message: `${filename} 文件已经存在！`,
                        type: 'error',
                        duration: 0
                    });
                    return false;
                }
                fs.writeFileSync(filePath, text);
                return true;
            },
            handleSelectSubmit(selects){
                this.selects = selects;
                this.tables = [];
                this.tableNames.forEach(async name => {
                    const sql = `SELECT * FROM information_schema.COLUMNS
                        WHERE table_schema = '${this.config.dbName}'
                        AND table_name = '${name}';`;

                    const fields = await this.$db.query(sql);
                    this.fields = fields;
                    this.name = name;
                    let myBatis = {name: name};

                    const [mpr, methods] = mapper.mapper(this, name);
                    myBatis.mapper = mpr;
                    myBatis.methods = methods;

                    if (this.selects.indexOf('select') >= 0) {
                        myBatis.select = select.select(this, name, fields);
                    }

                    if (this.selects.indexOf('selectList') >= 0) {
                        myBatis.selectList = select.selectList(this, name, fields);
                    }

                    if (this.selects.indexOf('selectPage&Total') >= 0) {
                        myBatis.selectPage = select.selectPage(this, name, fields);
                        myBatis.selectPageTotal = select.selectPageTotal(this, name, fields);
                    }

                    if (this.selects.indexOf('selectByKeyword') >= 0) {
                        this.ui.selectKeywordDialog.visible = true;
                    }

                    if (this.selects.indexOf('insert') >= 0) {
                        myBatis.insert = insert.insert(this, name, fields);
                    }

                    if (this.selects.indexOf('update') >= 0) {
                        myBatis.update = update.update(this, name, fields);
                    }

                    this.tables.push(myBatis);
                });
            },
            /** 关键字选择窗口 */
            handleSelectKeywordSubmit(keyword){
                const myBatis = this.tables[0];

                myBatis.selectByKeyword = select.selectByKeyword(this, this.name, keyword);
                myBatis.selectTotalByKeyword = select.selectTotalByKeyword(this, this.name, keyword);

                this.tables.splice(0, 1, myBatis);
            },
            /** 关闭处理 */
            handleClose(){
                this.visible = false;
                setTimeout(() => this.$emit('update:dialogVisible', false), 300);
            }
        }
    }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
    .create-mybatis-dialog {
    }
</style>